import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from '@/store';
import { Message, message, Loading } from 'element-ui';

Vue.use(VueRouter);
const router = new VueRouter({
    mode: 'hash',
    routes

});


//全局前置守卫
let loading;
router.beforeEach(async (to, from, next) => {
    let path = to.path;
    if (path === '/login') {
        next();
        return;
    }
    //校验当前用户是否登录
    let { info } = store.state;
    if (info === null) {
        //开启loading层
        loading = Loading.service({
            lock: true,
            text: '小主，奴家正在努力加载，请稍后...'
        });
        let res = await store.dispatch('queryProfileAsync');
        if (!res) {
            //没有登录
            Message.error('当前还没登录，清楚新登录');
            next(`./login?target=${to.path}`);
            return;
        }
        info = res;
    }
    //权限校验(访问拦截):根据meta获取目标路由的权限代码，再去登录者拥有的权限中校验是否存在，存在则正常调，不存在劝返
    let power = (info.power || "").split("|"),
        code = to.meta.code;
    if (code && !power.includes(code)){
        Message.error("您无权限访问此页面！");
        next(from.fullpath);
    }


        next();
});

//全局后置守卫
router.afterEach((to) => {
    if (loading) {
        loading.close()
    };
    let { title } = to.meta;
    title = title ? '-' + title : "";
    document.title = `新峰商城CMS系统${title}`
})
export default router;